<template>
  <div v-loading="handleLoading">
    <el-form
      ref="handleForm"
      :model="handleForm"
      :rules="handleRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="username" label="用户名">
            <el-input
              v-model="handleForm.username"
              placeholder="请输入用户名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sex" label="性别">
            <el-select
              v-model="handleForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option
                v-for="item in sexList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="phone" label="手机号码">
            <el-input
              v-model="handleForm.phone"
              type="number"
              placeholder="请输入手机号码"
              :maxlength="11"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="邮箱">
            <el-input
              v-model="handleForm.email"
              placeholder="请输入邮箱"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="nickName" label="昵称">
            <el-input
              v-model="handleForm.nickName"
              placeholder="请输入昵称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="dept" label="部门">
            <el-cascader
              v-model="handleForm.dept"
              placeholder="请选择部门"
              :options="deptList"
              :props="deptOptions"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="job" label="岗位">
            <el-select
              v-model="handleForm.job"
              placeholder="请选择岗位"
              clearable
            >
              <el-option
                v-for="item in jobList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="roles" label="角色">
            <el-select
              v-model="handleForm.roles"
              placeholder="请选择角色"
              clearable
            >
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="level !== 1 && item.level <= level"
                clearable
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="btns btn-right-container">
      <el-button type="normal" size="medium" @click="$emit('closeDialog', false)">
        关闭
      </el-button>
      <el-button type="primary" size="medium" @click="saveInfo">
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
import { addUsers, editUsers } from '@/api/users'
import { isMobile, isEmail } from '@/utils/validate'
export default {
  name: 'UsertHandle',
  props: {
    action: {
      type: String,
      default: 'add'
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    deptList: {
      type: Array,
      default: () => [],
      required: true
    },
    jobList: {
      type: Array,
      default: () => [],
      required: true
    },
    rolesList: {
      type: Array,
      default: () => [],
      required: true
    },
    level: {
      type: [Number, String],
      default: ''
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号码不能为空'))
      } else if (isMobile(value)) {
        callback()
      } else {
        callback(new Error('手机号码格式错误'))
      }
    }
    const validEmail = (rule, value, callback) => {
      if (value == '') {
        callback()
      } else if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    return {
      handleLoading: false,
      handleForm: {
        username: '',
        sex: '',
        phone: '',
        email: '',
        roles: '',
        job: '',
        dept: [],
        nickName: ''
      },
      handleRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        sex: [{
          required: false, message: '请选择性别', trigger: 'change'
        }],
        phone: [{
          required: true, validator: validPhone, trigger: 'blur'
        }],
        email: [{
          required: false, validator: validEmail, trigger: 'blur'
        }],
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        roles: [{
          required: true, message: '请新选择角色', trigger: 'change'
        }],
        job: [{
          required: true, message: '请新选择岗位', trigger: 'change'
        }],
        dept: [{
          required: true, message: '请新选择部门', trigger: 'change'
        }]
      },
      deptOptions: { // 部门级联参数
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true
      },
      sexList: [
        { label: '男', value: '男' },
        { label: '女', value: '女' }
      ]
    }
  },
  created() {
    console.log(this.formData)
    if (this.action == 'edit') {
      this.initHandleForm()
    }
  },
  methods: {
    saveInfo() {
      console.log(this.handleForm)
      this.$refs.handleForm.validate((valid) => {
        if (!valid) return
        this.handleLoading = true
        let fn = addUsers
        const param = {
          ...this.handleForm,
          enabled: true
        }
        param.roles = [{ id: param.roles }]
        param.dept = { id: param.dept[param.dept.length - 1] }
        param.job = { id: param.job }
        param.phone = parseInt(param.phone)
        if (this.action == 'edit') {
          fn = editUsers
          param.id = this.formData.id
        }
        fn(param).then(() => {
          this.$message({
            message: `${this.action == 'add' ? '新增' : '修改'}成功`,
            type: 'success'
          })
          this.$emit('closeDialog', true)
        }).catch((err) => {
          const errInfo = err.response && err.response.request.responseText ? JSON.parse(err.response.request.responseText) : ''
          this.$message({
            message: errInfo ? errInfo.message : `${this.action == 'add' ? '新增' : '修改'}失败`,
            type: 'error'
          })
        }).finally(() => {
          this.handleLoading = false
        })
      })
    },
    initHandleForm() {
      const validKeys = ['dept', 'job', 'roles']
      function setDepts(id, roles) {
        let result = []
        function deep(id1, roles1) {
          for (const role of roles1) {
            if (role.id == id1) {
              if (role.pid != 0) {
                result = [role.pid, role.id]
              } else {
                result.push(role.id)
              }
              break
            } else {
              if (role.children) {
                deep(id, role.children)
              }
            }
          }
        }
        deep(id, roles)
        return result
      }
      Object.keys(this.handleForm).forEach(key => {
        if (validKeys.includes(key)) {
          switch (key) {
            case 'dept':
              this.handleForm[key] = this.formData[key] ? setDepts(this.formData[key].id, this.deptList) : []
              break
            case 'roles':
              this.handleForm[key] = this.formData[key] && this.formData[key][0] ? this.formData[key][0].id : ''
              break
            default:
              this.handleForm[key] = this.formData[key] ? this.formData[key].id : ''
              break
          }
        } else {
          this.handleForm[key] = this.formData[key]
        }
      })
      console.log(this.handleForm)
      this.$nextTick(() => {
        this.$refs.handleForm.clearValidate()
      })
    }
  }
}
</script>
